/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lab2;

import actions.alert.AllTasksAction;
import actions.alert.CheckDeprecatedTasksAction;
import actions.alert.OneTaskAction;
import actions.alert.RecieveTasksAction;
import java.util.*;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import models.AlertWindowModel;

/**
 *
 * @author Кирилл
 */
public class AlertMultiTaskWindow extends javax.swing.JDialog {

    /**
     * Creates new form AlertMultiTaskWindow
     */
   // private List<Task> tasks = new ArrayList<>();
    private DefaultTableModel tableModel;
    private static AlertMultiTaskWindow instance = new AlertMultiTaskWindow(null, true);
   // private Manager manager = Manager.getInstance();
    private static int activeIndex;
    private AlertWindowModel alertModel = new AlertWindowModel();
            
    public static AlertMultiTaskWindow getInstance() {
        return instance;
    }

    public AlertMultiTaskWindow(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        tableModel = (DefaultTableModel) tasksTable.getModel();
        int columnNumber = tasksTable.getColumnModel().getColumnCount();
        for (int i = 0; i < columnNumber; i++) {
            tasksTable.getColumnModel().getColumn(i).setResizable(false);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        approveAllButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tasksTable = new javax.swing.JTable();
        approveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setAlwaysOnTop(true);
        setName("Active tasks"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        approveAllButton.setText("Ok all");
        approveAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                approveAllButtonActionPerformed(evt);
            }
        });

        tasksTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Task Name", "Start Time"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tasksTable.setAutoscrolls(false);
        tasksTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        tasksTable.setShowHorizontalLines(false);
        tasksTable.setShowVerticalLines(false);
        tasksTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tasksTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tasksTable);

        approveButton.setText("Ok");
        approveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                approveButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 705, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(approveButton)
                        .addGap(45, 45, 45)
                        .addComponent(approveAllButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cancelButton)))
                .addGap(16, 16, 16))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(approveAllButton)
                    .addComponent(approveButton)
                    .addComponent(cancelButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void approveAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_approveAllButtonActionPerformed
        // TODO add your handling code here:
        new AllTasksAction().doAction(alertModel);
        this.setVisible(false);
    }//GEN-LAST:event_approveAllButtonActionPerformed

    private void tasksTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tasksTableMouseClicked
        // TODO add your handling code here:
        if (evt.getClickCount() == 2) {
            activeIndex = tasksTable.getSelectedRow();
            AlertWindow aw = new AlertWindow(null, true, alertModel.getTasks().get(activeIndex));
            aw.setVisible(true);
        }
    }//GEN-LAST:event_tasksTableMouseClicked

    private void approveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_approveButtonActionPerformed
        // TODO add your handling code here:
        if (tasksTable.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(this, "No selected tasks");
        } else {
            int selectedRow = tasksTable.getSelectedRow();
            new OneTaskAction().doAction(alertModel);
           // manager.removeTask(tasks.get(selectedRow).getID());
            alertModel.getTasks().remove(selectedRow);
            tableModel.removeRow(selectedRow);

        }
        if (alertModel.getTasks().isEmpty()) {
            cancelButtonActionPerformed(null);
        }
    }//GEN-LAST:event_approveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        // TODO add your handling code here:
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        // TODO add your handling code here:
        while (tableModel.getRowCount() != 0) {
            tableModel.removeRow(0);
        }
        Iterator i = alertModel.getTasks().iterator();
        Task temp;
        Vector v;
        while (i.hasNext()) {
            temp = (Task) i.next();
            v = new Vector();
            v.add(0, temp.getName());
            v.add(1, temp.getStime().getTime());
            tableModel.addRow(v);
        }
    }//GEN-LAST:event_formWindowActivated

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AlertMultiTaskWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                AlertMultiTaskWindow dialog = new AlertMultiTaskWindow(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    public void addTasks(Calendar time) {
        alertModel.setDeprecated(false);
        alertModel.setAlertTime(time);
        new RecieveTasksAction().doAction(alertModel);
    }

    public boolean checkTasks() {
        new CheckDeprecatedTasksAction().doAction(alertModel);
        return alertModel.isDeprecated();
    }
    
    public void removeTask() {
        approveButtonActionPerformed(null);
        //tableModel.removeRow(activeIndex);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton approveAllButton;
    private javax.swing.JButton approveButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tasksTable;
    // End of variables declaration//GEN-END:variables

    
}
